/*
 * Publisher.java
 *
 * Created on 16 luglio 2005, 0.36
 *
 * Receive connections and notify it to the PublisherServer
 *
 * @version 1.1
 * @author Federico Paparoni
 *
 */

package com.javastaff.btfree;

import java.util.*;
import javax.microedition.io.*;
import javax.bluetooth.*;


public class Publisher extends Thread{
    
    private String nome;
    private PublisherServer ps;
    private StreamConnectionNotifier Server = null;
    private UUID uuid; 
    private int how;
    private boolean running;
    
    public Publisher(PublisherServer ps,String nome,String uuid,int how) {
        this.ps=ps;
        this.nome=nome;
        this.uuid=new UUID(uuid,false);
        this.how=how;
        this.running=true;
    }
    
    
    public void run() {
        try {
            LocalDevice local = LocalDevice.getLocalDevice();
            local.setDiscoverable( DiscoveryAgent.GIAC );
            Server = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+uuid.toString()+";master=false;authenticate=false;name="+nome);
            if (how==0) {
                while(running) {
                    StreamConnection conn = null;
                    conn = (StreamConnection)Server.acceptAndOpen();
                    ConnectionManager cm=new ConnectionManager(conn);
                    ps.signalConnection(cm);
                }
            }
            else {
                while(how>0) {
                    StreamConnection conn = null;
                    conn = (StreamConnection)Server.acceptAndOpen();
                    ConnectionManager cm=new ConnectionManager(conn);
                    ps.signalConnection(cm);
                    how--;
                }
            }
            
        }
        catch(Exception e) {
            ps.signalError(e.toString());
        }
    }
    
    public boolean closeConnection() {
        try{
            Server.close();
            return true;
        }
        catch(Exception e) {
            return false;
        }
    }
    
}
